import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteResultHandler;
import org.apache.commons.exec.ExecuteWatchdog;

import java.io.IOException;

public class WindowsSystemVariableExample {

    public static void main(String[] args) {
        // 获取系统变量示例
        getSystemVariable("JAVA_HOME");

        // 设置系统变量示例
        setSystemVariable("MY_VARIABLE", "C:\\MyPath");
    }


    // 使用Apache Commons Exec查看系统环境变量JAVA_HOME
    private static void getSystemVariable(String variableName) {
        CommandLine commandLine = new CommandLine("cmd");
        commandLine.addArgument("/c");
        commandLine.addArgument("echo %" + variableName + "%");

        DefaultExecutor executor = new DefaultExecutor();
        try {
            int exitValue = executor.execute(commandLine);
            System.out.println("System variable " + variableName + ": " + exitValue);
        } catch (ExecuteException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void setSystemVariable(String variableName, String variableValue) {
        CommandLine commandLine = new CommandLine("cmd");
        commandLine.addArgument("/c");
        commandLine.addArgument("setx");
        commandLine.addArgument(variableName);
        commandLine.addArgument(variableValue);

        DefaultExecutor executor = new DefaultExecutor();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); // 设置超时时间为60秒
        executor.setWatchdog(watchdog);

        try {
            executor.execute(commandLine, new ExecuteResultHandler() {
                @Override
                public void onProcessComplete(int exitValue) {
                    System.out.println("System variable " + variableName + " set successfully.");
                }

                @Override
                public void onProcessFailed(ExecuteException e) {
                    System.out.println("Failed to set system variable " + variableName);
                    e.printStackTrace();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
